// start.cpp
#include "start.h"
#include "ui_start.h"
#include "mainwindow.h"
#include <QPalette>
#include <QPixmap>
#include <QInputDialog>
#include <iostream>
#include <QtSql>
#include <QSqlDatabase>
#include <QApplication>
#include <QCoreApplication>

start::start(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::start)
{
    ui->setupUi(this);
    setFixedSize(900,600);
    // 创建QPalette对象
    QPalette palette;

    // 设置背景图片
    QPixmap backgroundImage(":/images/start.jpg");

    // 缩放背景图片以适应窗口大小
    backgroundImage = backgroundImage.scaled(this->size(), Qt::IgnoreAspectRatio);

    // 设置背景色为背景图片的颜色
    palette.setBrush(QPalette::Window, backgroundImage);


    // 将QPalette应用于窗口
    this->setPalette(palette);

    // 设置自动填充背景
    this->setAutoFillBackground(true);
    // 获取图片路径
    QString imagePath = ":/images/startgame_button.jpg";

    // 创建QPixmap并设置为按钮背景
    QPixmap image(imagePath);
    image.scaled(this->size(), Qt::IgnoreAspectRatio);
    ui->pushButton->setIcon(QIcon(image));
    ui->pushButton->setIconSize(image.size());
}

start::~start()
{
    delete ui;
}

void start::on_pushButton_clicked()
{
    bool open_ok;
    bool user_ok = false;
    QString account = QInputDialog::getText(this, tr("Enter User Account"), tr("Account:"), QLineEdit::Normal, "", &open_ok);
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setDatabaseName("mysql1"); //不是Database,记得别填错
    db.setUserName("root");
    db.setPassword("12345678");
    bool ok = db.open();

    /*
     * to delete
     */
    emit enterGame(account);


    if (ok) {
        std::cout << "Successfully connected to the database." << std::endl;

        // 创建用户表格（如果不存在的话）
        QSqlQuery createTableQuery("CREATE TABLE IF NOT EXISTS user_table (id INT PRIMARY KEY IDENTITY, account VARCHAR(255) UNIQUE NOT NULL)", db);

        // 查询数据库中是否已存在该用户
        QSqlQuery query;
        query.prepare("SELECT * FROM user_table WHERE account = :account");
        query.bindValue(":account", account);

        if (query.exec() && query.next()) {
            // 用户已存在，直接开始游戏
            QMessageBox::information(this, tr("Information"), tr("User already exists. Starting the game..."));
            user_ok = true;
        } else {
            QMessageBox::information(this, tr("Information"), tr("please create firstly"));
        }

        // 关闭数据库连接
        db.close();

        /*
         * to delete
         */
        // 打开主窗口并开始游戏
        if(true || user_ok){
            emit enterGame(account);
        }
    } else {
        std::cout << "Failed to connect to the database: " << db.lastError().text().toStdString() << std::endl;
    }

}

void start::on_pushButton_2_clicked() {
    bool open_ok;
    QString account = QInputDialog::getText(this, tr("Enter User Account"), tr("Account:"), QLineEdit::Normal, "", &open_ok);

    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setDatabaseName("mysql1");
    db.setUserName("root");
    db.setPassword("12345678");

    bool ok = db.open();

    if (ok) {
        std::cout << "Successfully connected to the database." << std::endl;

        // 创建用户表格（如果不存在的话）
        QSqlQuery createTableQuery("CREATE TABLE IF NOT EXISTS user_table (id INT PRIMARY KEY IDENTITY, account VARCHAR(255) UNIQUE NOT NULL)", db);

        // 查询数据库中是否已存在该用户
        QSqlQuery query;
        query.prepare("SELECT * FROM user_table WHERE account = :account");
        query.bindValue(":account", account);

        if (query.exec() && query.next()) {
            QMessageBox::information(this, tr("Information"), tr("User already exists."));
        } else {
            // 用户不存在，插入新用户信息
            QSqlQuery insertQuery;
            insertQuery.prepare("INSERT INTO user_table (account) VALUES (:account)");
            insertQuery.bindValue(":account", account);

            if (insertQuery.exec()) {
                QMessageBox::information(this, tr("Information"), tr("New user created"));
            } else {
                QMessageBox::information(this, tr("Information"), tr("Failed to create new user"));
            }
        }

        // 关闭数据库连接
        db.close();
    }
}
